package source.sort;

import org.junit.Test;

public class BinarySort {
    /**
     * 搜索旋转排序数组
     *
     * @param nums   旋转后的数组
     * @param target 目标值
     * @return 目标值的索引
     */
    public int search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (nums[mid] == target) return mid;

            if (nums[mid] >= nums[0]) {
                if (nums[mid] >= target && nums[l] <= target) r = mid - 1;
                else l = mid + 1;
            } else if (nums[mid] <= nums[nums.length - 1]) {
                if (nums[mid] <= target && nums[r] >= target) l = mid + 1;
                else r = mid - 1;
            }
        }

        return -1;
    }

    /**
     * 在排序数组中查找元素的第一个和最后一个位置
     * @param nums  排序数组
     * @param target 目标值
     * @return [first, last]
     */
    public int[] searchRange(int[] nums, int target) {
        int leftIndex = binarySearch(nums, target, true);
        int rightIndex = binarySearch(nums, target, false) - 1;
        if (leftIndex <= rightIndex && rightIndex < nums.length&& nums[leftIndex] == target && nums[rightIndex] == target)
            return new int[]{leftIndex, rightIndex};
        return new int[]{-1, -1};
    }

    private int binarySearch(int[] nums, int target, boolean findLeft){
        int l = 0, r = nums.length - 1;
        int result = nums.length;
        while (l <= r){
            int mid = (l + r) / 2;
            if (nums[mid] > target || (findLeft && nums[mid] >= target)){
                result = mid;
                r = mid - 1;
            } else l = mid + 1;
        }
        for(int i = 11 - 1,  j = 12 - 1; i >= 0 || j >=0; i--,j--){

        }

        return result;
    }

    @Test
    public void test() {
        StringBuilder stringBuilder =new StringBuilder();
        stringBuilder.append('0');
        System.out.println(stringBuilder.toString());
    }
}
